<?php

class BulletinController extends Zend_Controller_Action {
	const MAX_TRIES = 10;
	
	private $advertisement;
	private $user;
	private $mailQueue;
	private $advertisementResponse;
	private $city;
	private $country;
	private $localHelp;
	
	public function init() {
		$config = Zend_Registry::get ( 'config' );
		$versionNm = $config->project->version;
		$this->view->headLink()->prependStylesheet( $config->baseurl . '/'.$versionNm.'_css/datePicker.css' );
		$this->view->headScript ()->appendFile ( $config->baseurl . '/'.$versionNm.'_js/date.js' );
		$this->view->headScript ()->appendFile ( $config->baseurl . '/'.$versionNm.'_js/jquery.datePicker.js' );
		$this->view->headScript ()->appendFile ( $config->baseurl . '/'.$versionNm.'_js/jquery.validate.min.js' );
		
		$this->advertisement = new Advertisement ( );
		$this->user = new User ( );
		$this->mailQueue = new MailQueue ( );
		$this->advertisementResponse = new AdvertisementResponse ( );
		$this->city = new City ( );
		$this->country = new Country();
		$this->localHelp = new LocalHelp ( );
		
		$this->initView();
		$this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');		 
		$this->view->flashmsgs = $this->_flashMessenger->getMessages();
			
	}
	
	public function indexAction() {
		// action body
	}
	
	private function showSearch() {
		$searchForm = new Search ($this->_getParam(Constant::VAR_SEARCH_DATA_FROM_COUNTRY), $this->_getParam(Constant::VAR_SEARCH_DATA_TO_COUNTRY), urlencode($this->_helper->generator->getCurrentURI()));
		$this->view->searchForm = $searchForm;
	}
	
	/**
	 * Create post
	 */
	public function createAction() {
		$config = Zend_Registry::get ( 'config' );
		$versionNm = $config->project->version;
		$this->view->headLink()->prependStylesheet( $config->baseurl . '/'.$versionNm.'_css/datePicker.css' );
		$this->view->headScript ()->appendFile ( $config->baseurl . '/'.$versionNm.'_js/date.js' );
		$this->view->headScript ()->appendFile ( $config->baseurl . '/'.$versionNm.'_js/jquery.datePicker.js' );
		$this->view->headScript ()->appendFile ( $config->baseurl . '/'.$versionNm.'_js/jquery.validate.min.js' );
		$this->view->headScript ()->appendFile ( $config->baseurl . '/'.$versionNm.'_js/create.js' );
		$this->view->class = "post";
		
		$country = $this->country->findById(209);
		$form = new CreateOrUpdatePost ( null, null, $this->_getParam(Constant::VAR_SEARCH_DATA_FROM_COUNTRY), $this->_getParam(Constant::VAR_SEARCH_DATA_TO_COUNTRY) );
		$this->view->form = $form;
		$this->processFormData ( $form, null );
		
		$this->showSearch();
		
	}
	
	/**
	 * Update advertisement action
	 */
	public function updateAction() {
		$id = $this->_getParam ( 'id' );
		$password = $this->_getParam ( 'password' );
		
		$advertisement = $this->advertisement->findById ( $id );
		if (isset ( $advertisement )) {
			$fromCountry = City::getCountry(Advertisement::getFromCity($advertisement->id));
			$toCountry = City::getCountry(Advertisement::getToCity($advertisement->id));
			$form = new CreateOrUpdatePost ( $advertisement, $password, $fromCountry->id, $toCountry->id );
			$this->view->form = $form;
			$this->processFormData ( $form, $advertisement );
		} else {
			throw new Exception ( 'Unable to find the advertisement!' );
		}
	}
	
	/**
	 * Process form data. Update and create new post.
	 * 
	 * @param $form
	 * @param $advertisement
	 * @param $city
	 */
	private function processFormData($form, $advertisement) {
		if ($this->getRequest ()->isPost ()) {
			if ($form->isValid ( $_POST )) {
//				$isValid = $this->_helper->common->validReCaptcha ( $this->_getAllParams() );
//				if ($isValid) {
					$password = $form->getValue (Advertisement::PASSWORD);
					if ($password != $advertisement->password) {
						throw new Exception ( '没有权限修改该帖子' );
					}
					$from_city = $form->getValue (Advertisement::FROM_CITY);
					$to_city = $form->getValue (Advertisement::TO_CITY);
					$departure_time = $form->getValue (Advertisement::DEPARTURE_TIME);
					$arrival_time = $form->getValue (Advertisement::ARRIVAL_TIME);
					$id = $form->getValue (Advertisement::ID);
					$name = $form->getValue (User::NAME);
					$email = $form->getValue (User::EMAIL);
					$mobile = $form->getValue (User::MOBILE);
					$type = $form->getValue (Advertisement::TYPE);
					$weight = $form->getValue (Advertisement::WEIGHT);
					$description = $form->getValue (Advertisement::DESCRIPTION);
					
					$db = Zend_Registry::get ( 'db' );
					$db->beginTransaction ();
					$data = array ('name' => trim ( $name ), 'email' => trim ( $email ), 'mobile' => trim ( $mobile ) );
					$user = $this->user->addUser ( $data );
					$title = ($type=="want" ? "【求托 】" : "【可托】 ").$this->city->findById($from_city)->name_cn." → ".$this->city->findById($to_city)->name_cn." (".$weight."公斤)";
					$data = array ('user_id' => $user->id, 'title'=>$title, 'description' => isset ( $description ) ? $description : null, 'weight' => isset ( $weight ) ? $weight : 0, 'type' => $type, 'from_city' => $from_city, 'to_city' => $to_city, 'departure_time' => $departure_time, 'arrival_time'=>$arrival_time, 'created' => $this->_helper->generator->generateCurrentTime (), 'modified' => $this->_helper->generator->generateCurrentTime ());
					if (isset ( $advertisement )) {
						$data [Advertisement::ID] = $advertisement->id;
						$this->advertisement->addOrUpdateAdvertisement ( $data );
					} else {
						$data [Advertisement::PASSWORD] = $this->generatePassword ( $email );
						$advertisement = $this->advertisement->addOrUpdateAdvertisement ( $data );
						// send email to creator
						$message = MailTemplate::getCreationEmailMessage ( $advertisement );
						$this->mailQueue->addToQueue ( MailType::USER, null, MailTemplate::SUBJECT_CREATE_POST, Constant::SYSTEM_MAIL, $email, $message, $this->_helper->generator->generateCurrentTime () );
					}
					$db->commit ();
		
        			$this->_flashMessenger->addMessage("您的帖子已经成功发布。如果在十分钟内未收到系统邮件，请【【务必】】确认它未被归入您的垃圾邮件 -_-||　因为其它用户将靠这个邮件与您取得联系！谢谢！");
					$this->_redirect ( '/' . strtolower ( $this->city->findById ( $city_id )->name ) . '/bulletin/list' );
//				}
			}
		}
	}
	
	/**
	 * Get value that can be saved in db about rent measurement.
	 * 
	 * @param $valueFromForm value from form
	 */
	private function getFromForm($valueFromForm) {
		switch ($valueFromForm) {
			case 1 :
				$value = Advertisement::RENT_DAILY;
				break;
			case 0 :
				$value = Advertisement::RENT_MONTHLY;
				break;
			default :
				$value = Advertisement::RENT_MONTHLY;
		}
		return $value;
	}
	
	/**
	 * @param $email
	 * @return return generated unique password
	 */
	private function generatePassword($email) {
		$seed = $email . rand ( 0, 10000 ) . $this->_helper->generator->generateCurrentTime ();
		$password = md5 ( $seed );
		$object = $this->advertisement->findAdvertisementByPassword ( $password );
		$numOfTry = 0;
		while ( isset ( $object ) && $numOfTry < self::MAX_TRIES ) {
			$seed = $email . rand ( 0, 10000 ) . $this->_helper->generator->generateCurrentTime ();
			$password = md5 ( $seed );
			$object = $this->advertisement->findAdvertisementByPassword ( $password );
			$numOfTry ++;
		}
		if (isset ( $object )) {
			throw new Exception ( 'Unable to create unique password!' );
		}
		return $password;
	}
	
	/**
	 * List all post action.
	 */
	public function listAction() {
		$config = Zend_Registry::get ( 'config' );
		$versionNm = $config->project->version;
		$this->view->headScript ()->appendFile ( $config->baseurl . '/'.$versionNm.'_js/jquery.cookie.js' );
		$this->view->headScript ()->appendFile ( $config->baseurl . '/'.$versionNm.'_js/list.js' );
		
		if ($this->_helper->user->isLoggedIn()) {
			$countryId = 209;
			$country = $this->_helper->location->getCountryFromIp($this->_helper->generator->getIpAddress());
			if (! isset ( $country )) {
				throw new Exception ( '暂时不支持所在城市!' );
			}
			SessionUtil::setProperty(Constant::VAR_USER_DATA_COUNTRY, $country);
			
			$this->showSearch();
			// load data from search data session
			$searchData = SessionUtil::getProperty(Constant::SEARCH_DATA);
			
			if (empty ( $searchData ) || !isset($searchData)) {
				$advertisements = $this->advertisement->findAll();
			} else {
				$advertisements = $this->advertisement->searchByCriteria ( $searchData );
			}
			
			$this->view->currentURI = urlencode($this->_helper->generator->getCurrentURI());
			
			
			//$this->view->advertisements = $advertisements;
			$this->view->paginator = $this->_helper->paginator ( $this->_getParam ( 'page', 1 ), $advertisements );
		} else {
			$this->_redirect($config->baseurl."/user/login/?next=".urlencode($this->_helper->generator->getCurrentURI()));
		}
		
	}
	
	/**
	 * View detail post action.
	 */
	public function viewAction() {
		$config = Zend_Registry::get ( 'config' );
		$versionNm = $config->project->version;
		$this->view->headScript ()->appendFile ( $config->baseurl . '/'.$versionNm.'_js/jquery.validate.min.js' );
		$this->view->headScript ()->appendFile ( $config->baseurl . '/'.$versionNm.'_js/view.js' );
		
		if ($this->_helper->user->isLoggedIn()) {
			$loggedInUser = $this->_helper->user->getUserData();
			$this->view->class = "view";
			$id = $this->_getParam ( 'id' );
			$advertisement = $this->advertisement->findById ( $id );
			if (isset ( $advertisement )) {
				$this->view->viewMode = 'detail';
				$this->view->advertisement = $advertisement;
				$form = new SendIntrestMail ( $loggedInUser, $advertisement );
				$this->view->form = $form;
				
				$advertisement = $this->advertisement->findById ( $id );
				$user = Advertisement::getUser ( $id );
				$this->view->userComments = $this->getUserComments($user);
				$userCommentForm = new UserCommentForm($loggedInUser, $advertisement, urlencode($this->_helper->generator->getCurrentURI()));
				$this->view->userCommentForm = $userCommentForm;
				
				$this->view->pageTitle = $advertisement->title . "| 托个行李 ";
				$pageDesc = "";
				if ($advertisement->type == "want") {
					$this->view->pageImage = "want";
					$pageDesc = $pageDesc . "出发时间:" . $advertisement->departure_time. " | ";
					$pageDesc = $pageDesc . "抵达时间" . $advertisement->arrival_time . " | ";
					$pageDesc = $pageDesc . "\n描述:" . $advertisement->description;
				} else {
					$this->view->pageImage = "lease";
					$pageDesc = $pageDesc . "出发时间:" . $advertisement->departure_time. " | ";
					$pageDesc = $pageDesc . "抵达时间" . $advertisement->arrival_time . " | ";
					$pageDesc = $pageDesc . "\n描述:" . $advertisement->description;
				}
				
				$this->view->pageDesc = $pageDesc;
				
				
				$this->showSearch();
				
				if ($this->getRequest ()->isPost ()) {
					if ($form->isValid ( $_POST )) {
	//					$isValid = $this->_helper->common->validReCaptcha ($this->_getAllParams());
	//					if ($isValid) {
							$id = $form->getValue ( 'id' );
							$sendUserId = $form->getValue("user_id");
							$sendUser = $this->user->findById($sendUserId);
							$email = $sendUser->email;
//								$city = $form->getValue ( 'city' );
//								// sender name
//								$name = $form->getValue ( 'name' );
//								// sender email
//								$email = $form->getValue ( 'email' );
							// body
							$body = $form->getValue ( 'body' );
							$advertisement = $this->advertisement->findById ( $id );
							$user = Advertisement::getUser ( $id );
							//$this->_helper->swiftEmail->sendEmail($body, Advertisement::getUser($advertisement->id)->email, $email, '租个房子');
							$db = Zend_Registry::get ( 'db' );
							$db->beginTransaction ();
//							$data = array ('name' => trim ( $name ), 'email' => trim ( $email ) );
//							$sendUser = $this->user->addUser ( $data );
							$message = MailTemplate::getEmailMessage ( $name, $email, $user->email, $body, $advertisement, MailTemplate::SENDER_MAIL_BODY );
							$subject = MailTemplate::getEmailSubject ( $advertisement->title, MailTemplate::SUBJECT_SEND_TO_OWNER );
							$mailId = $this->mailQueue->addToQueue ( MailType::USER, $name, $subject, $email, $user->email, $message, $this->_helper->generator->generateCurrentTime () );
							// add advertisement response
							$this->advertisementResponse->addAdvertisementResponse ( $id, $sendUserId, $mailId );
							
							$message = MailTemplate::getEmailMessage ( $name, $email, $user->email, $body, $advertisement, MailTemplate::SENDER_RECIEPT_BODY );
							$subject = MailTemplate::getEmailSubject ( $advertisement->title, MailTemplate::SUBJECT_SENDER_RECEIPT );
							$this->mailQueue->addToQueue ( MailType::USER, $name, $subject, Constant::SYSTEM_MAIL, $email, $message, $this->_helper->generator->generateCurrentTime () );
							$this->_flashMessenger->addMessage("您的邮件已成功发给贴主了！请等待回音！谢谢您的支持！！");
							$db->commit ();
							$this->_redirect ( '/bulletin/view/id/' . $advertisement->id );
	//					} else {
	////						throw new Exception ( '验证码错误!' );
	//					}
					}
				}
			
			} else {
				throw new Exception ( '帖子ID缺失或者帖子未找到!' );
			}
		} else {
			$this->_redirect($config->baseurl."/user/login/?next=".urlencode($this->_helper->generator->getCurrentURI()));
		}
	
	}
	
	/**
	 * Get all comment to given user, sorted by created desc.
	 * 
	 * @param $user
	 * @return list of comments
	 */
	private function getUserComments($user) {
		$ret = array();
		$ret = User::getComments($user);
		return $ret;
	}
	
	/**
	 * Close post action.
	 */
	public function closeAction() {
		$id = $this->_getParam ( 'id' );
		$advertisement = $this->advertisement->findById ( $id );
	
	}
	
	/**
	 * Post admin action.
	 */
	public function adminAction() {
		$config = Zend_Registry::get ( 'config' );
		$versionNm = $config->project->version;
		$this->view->headScript ()->appendFile ( $config->baseurl . '/'.$versionNm.'_js/jquery.validate.min.js' );
		$this->view->headScript ()->appendFile ( $config->baseurl . '/'.$versionNm.'_js/create.js' );
		
		$id = $this->_getParam ( 'id' );
		$advertisement = $this->advertisement->findById ( $id );
		if (empty ( $advertisement )) {
			throw new Exception ( 'ID 缺失或者帖子没找到!' );
		} else {
			$this->view->view_id = $id;
			$form = new AdminPost ( $advertisement );
			$this->view->form = $form;
			if ($this->getRequest ()->isPost ()) {
				if ($form->isValid ( $_POST )) {
//					$isValid = $this->_helper->common->validReCaptcha ( $this->_getAllParams() );
//					if ($isValid) {
						$config = Zend_Registry::get("config");
						$baseurl = $config->baseurl;
						$action = $form->getValue ( 'action' );
						$password = $form->getValue ( 'password' );
						switch ($action) {
							case 0 :
								if ($password == $advertisement->password) {
									$db = Zend_Registry::get ( 'db' );
									$db->beginTransaction ();
									$this->advertisement->closeAdvertisement ( $id );
									$db->commit ();
									$this->_redirect ( $baseurl.'/bulletin/list' );
								} else {
									throw new Exception ( '没有权限关闭该帖子!' );
								}
								break;
							case 1 :
								if ($password == $advertisement->password) {
									$form = new CreateOrUpdatePost ( $advertisement, $password, 209 );
									$this->view->form = $form;
								} else {
									throw new Exception ( '没有权限修改该帖子!' );
								}
								break;
							case 2 :
								if ($password == '12345678') {
									$db = Zend_Registry::get ( 'db' );
									$db->beginTransaction ();
									$this->advertisement->deleteAdvertisement ( $id );
									$db->commit ();
									$this->_redirect ( $baseurl.'/bulletin/list' );
								} else {
									throw new Exception ( '没有权限删除该帖子!' );
								}
								break;
						}
					}
				}
//			}
		}
	}
	
	public function createsessionAction() {
		$aNamespace = new Zend_Session_Namespace ( Constant::USER_DATA );
		$aNamespace->city = $this->_getParam ( 'city' );
		exit ();
	}
	
	/*AJAX FUNCTIONS*/
	public function citylistajaxAction() {
		
		$this->_helper->viewRenderer->setNoRender (); //view info disabled
		$this->_helper->getHelper ( 'layout' )->disableLayout (); //template disabled
		

		$countryId = $this->getRequest ()->getParam ( 'countryId' );
		
		if ($countryId != 0)
			$cities = Country::getCityByCountryAsArray( $countryId );
		else
			$cities = null;

			
		$list = $this->view->selectList ( $cities );
		$returnJson = array ("list" => $list, "exist" => ($cities != null && count ( $cities ) > 0) );
		echo Zend_Json::encode ( $returnJson );
	}
	
	public function testAction() {
	/*
		$form = new ReCaptcha();
		$this->view->form = $form;
		if ($this->_request->isPost()) {
			$config = Zend_Registry::get("config");
		$publickey = $config->recaptcha->public->key;
		$privatekey = $config->recaptcha->private->key;
                $recaptcha = new Zend_Service_ReCaptcha($publickey, $privatekey);
			$result = $recaptcha->verify($this->_getParam('recaptcha_challenge_field'),
                                             $this->_getParam('recaptcha_response_field'));
			print_r($result);
			if ($result->isValid()){
			echo "right";
		} else {
			echo "wrong";
		}
											 
		}*/
		
		$form = new ReCaptcha();
		$this->view->form = $form;
        if ($this->_request->isPost()) {
			//if ($form->isValidPartial ( $_POST )) {
				$config = Zend_Registry::get("config");
		$publickey = $config->recaptcha->public->key;
		$privatekey = $config->recaptcha->private->key;
		$recaptcha = new Zend_Service_ReCaptcha($publickey, $privatekey);
		$result = $recaptcha->verify($this->_getParam('recaptcha_challenge_field'), $this->_getParam('recaptcha_response_field'));
		print_r($result);
			
            	$isValid = $this->_helper->common->validReCaptcha($this->_getAllParams());
            	if (!$isValid) {
                	echo "adfa";
                    //ReCaptcha validation error
                    //Your action here...
               } else {
               	echo "right";
               }
            //}
        }
        
	}
	
}

